import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useUserStore } from '../../store/userStore';

// 问题类型定义
interface Question {
  id: string;
  text: string;
  category: string;
  options: {
    text: string;
    value: number;
  }[];
}

// 推荐类型定义
interface Recommendation {
  category: string;
  text: string;
  impact: number; // 减少碳排放的潜力（kg CO2）
}

// 问卷数据
const questions: Question[] = [
  {
    id: 'transport-daily',
    text: '您日常通勤主要使用什么交通工具？',
    category: '交通',
    options: [
      { text: '私家汽车（单人驾驶）', value: 12 },
      { text: '拼车', value: 6 },
      { text: '公共交通（公交/地铁）', value: 4 },
      { text: '电动车/自行车', value: 1 },
      { text: '步行', value: 0 }
    ]
  },
  {
    id: 'transport-distance',
    text: '您的日常通勤单程距离是多少？',
    category: '交通',
    options: [
      { text: '5公里以内', value: 2 },
      { text: '5-15公里', value: 5 },
      { text: '15-30公里', value: 8 },
      { text: '30-50公里', value: 12 },
      { text: '50公里以上', value: 15 }
    ]
  },
  {
    id: 'diet-type',
    text: '您的饮食习惯是？',
    category: '饮食',
    options: [
      { text: '大量肉食（每天多餐含肉）', value: 10 },
      { text: '普通饮食（每天1-2餐含肉）', value: 7 },
      { text: '低肉饮食（每周仅数次含肉）', value: 4 },
      { text: '素食（含奶蛋）', value: 2 },
      { text: '纯素食（不含任何动物产品）', value: 1 }
    ]
  },
  {
    id: 'diet-local',
    text: '您购买的食物多数来自？',
    category: '饮食',
    options: [
      { text: '不清楚来源/多为进口食品', value: 5 },
      { text: '超市购买（混合来源）', value: 3 },
      { text: '主要为本地/季节性食品', value: 1 },
      { text: '自种或社区支持农业项目', value: 0 }
    ]
  },
  {
    id: 'home-energy',
    text: '您家庭使用的电力主要来源是？',
    category: '居住',
    options: [
      { text: '传统电网（煤电为主）', value: 8 },
      { text: '部分绿色能源', value: 5 },
      { text: '选择了绿色电力计划', value: 3 },
      { text: '自家太阳能/其他可再生能源', value: 1 }
    ]
  },
  {
    id: 'home-heating',
    text: '您家庭采暖主要使用什么能源？',
    category: '居住',
    options: [
      { text: '煤炭/燃油锅炉', value: 10 },
      { text: '天然气', value: 7 },
      { text: '电力（含热泵）', value: 5 },
      { text: '可再生能源（地热/太阳能等）', value: 1 },
      { text: '不需要采暖', value: 0 }
    ]
  },
  {
    id: 'home-size',
    text: '您的住所面积多大？',
    category: '居住',
    options: [
      { text: '150平方米以上', value: 8 },
      { text: '100-150平方米', value: 6 },
      { text: '50-100平方米', value: 4 },
      { text: '50平方米以下', value: 2 }
    ]
  },
  {
    id: 'waste-recycle',
    text: '您多久会回收可回收垃圾？',
    category: '废弃物',
    options: [
      { text: '几乎不回收', value: 6 },
      { text: '偶尔回收', value: 4 },
      { text: '经常回收', value: 2 },
      { text: '始终坚持回收', value: 1 }
    ]
  },
  {
    id: 'waste-reduce',
    text: '您多大程度上减少一次性物品使用？',
    category: '废弃物',
    options: [
      { text: '很少考虑', value: 5 },
      { text: '有时避免使用', value: 3 },
      { text: '尽量使用可重复使用物品', value: 1 },
      { text: '积极践行零废弃生活方式', value: 0 }
    ]
  },
  {
    id: 'consumption',
    text: '您购买新物品的频率？',
    category: '消费',
    options: [
      { text: '经常购买（每周多次）', value: 8 },
      { text: '适中（每月数次）', value: 5 },
      { text: '很少（仅在必要时）', value: 2 },
      { text: '极少（优先重用/修理旧物）', value: 1 }
    ]
  }
];

// 推荐建议数据
const recommendations: Recommendation[] = [
  {
    category: '交通',
    text: '考虑使用公共交通或拼车上下班，每周至少三天。',
    impact: 25
  },
  {
    category: '交通',
    text: '短途出行（5公里内）选择步行或骑行。',
    impact: 15
  },
  {
    category: '交通',
    text: '考虑购买电动车或混合动力车，减少燃油消耗。',
    impact: 50
  },
  {
    category: '饮食',
    text: '尝试每周至少一天素食日。',
    impact: 20
  },
  {
    category: '饮食',
    text: '购买当地和季节性食品，减少食物里程。',
    impact: 10
  },
  {
    category: '饮食',
    text: '减少食物浪费，合理规划饮食和储存。',
    impact: 15
  },
  {
    category: '居住',
    text: '将家中照明更换为LED灯泡。',
    impact: 10
  },
  {
    category: '居住',
    text: '优化家中保温，减少能源流失。',
    impact: 30
  },
  {
    category: '居住',
    text: '使用可编程恒温器，优化温度设置。',
    impact: 20
  },
  {
    category: '居住',
    text: '考虑安装太阳能板或参与绿色电力计划。',
    impact: 40
  },
  {
    category: '废弃物',
    text: '建立完善的家庭回收系统，确保最大程度回收利用。',
    impact: 15
  },
  {
    category: '废弃物',
    text: '减少使用一次性塑料制品，选择可重复使用的替代品。',
    impact: 10
  },
  {
    category: '消费',
    text: '延长物品使用寿命，优先考虑修理而非替换。',
    impact: 25
  },
  {
    category: '消费',
    text: '选择有环保认证的产品和品牌。',
    impact: 15
  }
];

// 评分解释
const footprintExplanations = [
  { maxValue: 15, text: '恭喜您！您的碳足迹非常低，处于生态友好水平。', color: '#4CAF50' },
  { maxValue: 30, text: '您的碳足迹低于平均水平，继续保持并寻找进一步改进的空间。', color: '#8BC34A' },
  { maxValue: 45, text: '您的碳足迹处于中等水平，通过适当调整生活方式可以显著减少。', color: '#FFC107' },
  { maxValue: 60, text: '您的碳足迹略高，建议关注几个主要排放领域进行改善。', color: '#FF9800' },
  { maxValue: 100, text: '您的碳足迹较高，需要认真考虑如何减少日常活动的环境影响。', color: '#F44336' }
];

export const CarbonCalculator: React.FC = () => {
  const { user, setUser } = useUserStore();
  const [answers, setAnswers] = useState<Record<string, number>>({});
  const [currentStep, setCurrentStep] = useState(0);
  const [completed, setCompleted] = useState(false);
  const [totalCarbon, setTotalCarbon] = useState(0);
  const [categoryScores, setCategoryScores] = useState<Record<string, number>>({});
  const [personalRecommendations, setPersonalRecommendations] = useState<Recommendation[]>([]);
  const [footprintExplanation, setFootprintExplanation] = useState<{ text: string, color: string }>({ text: '', color: '' });
  const [showResults, setShowResults] = useState(false);

  // 监听answers变化，如果所有问题都回答了，则自动计算结果，组件挂载
  useEffect(() => {
    const allQuestionsAnswered = questions.every(q => answers[q.id] !== undefined);
    if (allQuestionsAnswered && Object.keys(answers).length === questions.length) {
      calculateResults();
    }
  }, [answers]);

  // 从localStorage加载数据
  useEffect(() => {
    const savedResults = localStorage.getItem('carbonCalculatorResults');
    if (savedResults) {
      const results = JSON.parse(savedResults);
      setAnswers(results.answers);
      setTotalCarbon(results.totalCarbon);
      setCategoryScores(results.categoryScores);
      setPersonalRecommendations(results.personalRecommendations);
      setFootprintExplanation(results.footprintExplanation);
      setCompleted(results.completed);
      setShowResults(true);
    }
  }, []);

  // 计算结果并生成个性化建议
  const calculateResults = () => {
    // 计算总分和分类得分
    const total = Object.values(answers).reduce((sum, value) => sum + value, 0);

    // 计算各类别得分
    const categories = Array.from(new Set(questions.map(q => q.category)));
    const catScores: Record<string, number> = {};

    categories.forEach(cat => {
      const catQuestions = questions.filter(q => q.category === cat);
      const catAnswers = catQuestions.filter(q => answers[q.id] !== undefined);

      if (catAnswers.length > 0) {
        const catTotal = catAnswers.reduce((sum, q) => sum + (answers[q.id] || 0), 0);
        catScores[cat] = catTotal;
      } else {
        catScores[cat] = 0;
      }
    });

    setCategoryScores(catScores);

    // 生成个性化建议
    const highestCategories = Object.entries(catScores)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 2)
      .map(([cat]) => cat);

    // 从高分类别中选取建议
    const catRecs = recommendations
      .filter(rec => highestCategories.includes(rec.category))
      .sort((a, b) => b.impact - a.impact)
      .slice(0, 3);

    // 额外添加1-2个随机建议
    const otherRecs = recommendations
      .filter(rec => !highestCategories.includes(rec.category))
      .sort(() => Math.random() - 0.5)
      .slice(0, 2);

    setPersonalRecommendations([...catRecs, ...otherRecs]);

    // 设置评分解释
    const explanation = footprintExplanations.find(exp => total <= exp.maxValue) ||
      footprintExplanations[footprintExplanations.length - 1];
    setFootprintExplanation(explanation);

    // 设置总碳排放量
    setTotalCarbon(total);

    // 更新用户数据
    if (user) {
      setUser({
        ...user,
        carbonFootprint: total
      });
    }

    // 标记完成
    setCompleted(true);
    setShowResults(true);



    // 保存到localStorage
    localStorage.setItem('carbonCalculatorResults', JSON.stringify({
      answers,
      totalCarbon,
      categoryScores,
      personalRecommendations,
      footprintExplanation,
      completed
    }));

  };

  // 处理回答问题
  const handleAnswer = (questionId: string, value: number) => {
    setAnswers({
      ...answers,
      [questionId]: value
    });

    // 自动前进到下一个问题
    if (currentStep < questions.length - 1) {
      setCurrentStep(currentStep + 1);
    } else {
      // 已经是最后一个问题，计算结果
      console.log("已完成所有问题，开始计算结果...");
      calculateResults();
    }
  };

  // 重新开始测试
  const handleRestart = () => {
    setAnswers({});
    setCurrentStep(0);
    setCompleted(false);
    setShowResults(false);
    setTotalCarbon(0);
    setCategoryScores({});
    setPersonalRecommendations([]);

    // 清除localStorage中的数据
    localStorage.removeItem('carbonCalculatorResults');
  };

  return (
    <div style={{ padding: '24px' }}>
      {!showResults ? (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          <h2>碳足迹计算器</h2>
          <p>回答以下问题，了解您的碳足迹水平：</p>

          <div style={{ marginTop: '20px' }}>
            <h3>{questions[currentStep].category}</h3>
            <h4>{questions[currentStep].text}</h4>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
              {questions[currentStep].options.map((option, index) => (
                <button
                  key={index}
                  onClick={() => handleAnswer(questions[currentStep].id, option.value)}
                  style={{
                    padding: '10px 15px',
                    border: '1px solid #ddd',
                    borderRadius: '8px',
                    background: answers[questions[currentStep].id] === option.value ? '#E8F5E9' : 'white',
                    cursor: 'pointer',
                    textAlign: 'left'
                  }}
                >
                  {option.text}
                </button>
              ))}
            </div>
          </div>
        </motion.div>
      ) : (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          <h2>您的碳足迹分析结果</h2>
          <div style={{
            padding: '20px',
            backgroundColor: footprintExplanation.color + '22',
            borderRadius: '12px',
            marginBottom: '20px'
          }}>
            <h3 style={{ color: footprintExplanation.color, marginTop: 0 }}>
              总碳足迹：{totalCarbon.toFixed(1)} kg CO₂/天
            </h3>
            <p style={{ color: footprintExplanation.color }}>
              {footprintExplanation.text}
            </p>
          </div>

          <h3>分类详情</h3>
          <div style={{ marginBottom: '20px' }}>
            {Object.entries(categoryScores).map(([category, score]) => (
              <div key={category} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px' }}>
                  <span>{category}</span>
                  <span>{score.toFixed(1)} kg CO₂/天</span>
                </div>
                <div style={{
                  width: '100%',
                  height: '8px',
                  backgroundColor: '#f0f0f0',
                  borderRadius: '4px'
                }}>
                  <div style={{
                    width: `${(score / totalCarbon * 100)}%`,
                    height: '100%',
                    backgroundColor: footprintExplanation.color,
                    borderRadius: '4px'
                  }} />
                </div>
              </div>
            ))}
          </div>

          <h3>个性化建议</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
            {personalRecommendations.map((rec, index) => (
              <div
                key={index}
                style={{
                  padding: '15px',
                  backgroundColor: 'white',
                  borderRadius: '8px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.05)'
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px' }}>
                  <strong>{rec.category}</strong>
                  <span>可减少 {rec.impact} kg CO₂/年</span>
                </div>
                <p style={{ margin: 0 }}>{rec.text}</p>
              </div>
            ))}
          </div>

          <button
            onClick={handleRestart}
            style={{
              marginTop: '20px',
              padding: '10px 20px',
              backgroundColor: '#4CAF50',
              color: 'white',
              border: 'none',
              borderRadius: '8px',
              cursor: 'pointer'
            }}
          >
            重新计算
          </button>
        </motion.div>
      )}
    </div>
  );
};

export default CarbonCalculator; 